import {
    getPlayerData,
    storagePlayerData,
    ensureGroupAndPlayerExist,
    formatCurrency,
    getConfig,
    checkPermission
} from "../function/function.js";

export class SlaveRanking extends plugin {
    constructor() {
        super({
            name: '[Sm]奴隶排位赛',
            dsc: '参加奴隶排位赛获取奖励',
            event: 'message',
            priority: 1,
            rule: [
                { reg: /^[#\/]排位赛$/, fnc: 'showRanking' },
                { reg: /^[#\/]参加排位赛\s*(\d+)$/, fnc: 'joinRanking' }
            ]
        })

        this.opponents = [
            { name: '流浪剑客', score: 800, specialEffect: '剑术精湛，容易造成暴击' },
            { name: '江湖大侠', score: 1200, specialEffect: '内力深厚，防御力强' },
            { name: '武林高手', score: 1600, specialEffect: '轻功绝顶，闪避率高' },
            { name: '绝世高手', score: 2000, specialEffect: '武学通神，全面强化' },
            { name: '隐世门派弟子', score: 1400, specialEffect: '招式诡异，难以预测' },
            { name: '江湖杀手', score: 1100, specialEffect: '出手狠辣，伤害提升' },
            { name: '武馆教习', score: 900, specialEffect: '经验丰富，稳扎稳打' },
            { name: '散打高手', score: 1300, specialEffect: '近身搏斗见长' }
        ]

        this.events = [
            { name: '天气晴朗', effect: 1.1, desc: '状态绝佳' },
            { name: '狂风暴雨', effect: 0.9, desc: '行动受限' },
            { name: '月黑风高', effect: 1.2, desc: '战力提升' },
            { name: '人来人往', effect: 0.95, desc: '注意力分散' },
            { name: '良辰吉日', effect: 1.15, desc: '运势加成' }
        ]
    }

    async joinRanking(e) {
        if (!e.isGroup) return e.reply(['该功能只能在群内使用']);
        const ID = [e.user_id, e.group_id];

        // 确保群组和玩家数据存在
        await ensureGroupAndPlayerExist(ID[1], ID[0]);

        try {
            const userData = await getPlayerData(ID[1], ID[0]);

            // 获取目标奴隶ID
            let slave;
            if (e.at) {
                slave = e.at;
            } else {
                slave = parseInt(e.msg.match(/\d+/)[0]);
            }

            if (!userData.slave.includes(slave)) {
                return e.reply(['你不是该奴隶的主人']);
            }

            const config = getConfig();
            const currentTime = Math.floor(Date.now() / 1000);

            // 检查冷却时间
            if (!checkPermission(e) && userData.lastRankingTime && currentTime - userData.lastRankingTime < config.ranking.cooldown) {
                const remainingTime = config.ranking.cooldown - (currentTime - userData.lastRankingTime);
                const minutes = Math.floor(remainingTime / 60);
                const seconds = remainingTime % 60;
                return e.reply([`排位赛冷却中，剩余时间：${minutes}分${seconds}秒`]);
            }

            const slaveData = await getPlayerData(ID[1], slave);

            // 初始化排位数据
            if (!slaveData.ranking) {
                slaveData.ranking = {
                    score: 1000,    // 初始分数
                    tier: '青铜',   // 初始段位
                    matches: 0      // 比赛场次
                };
            }

            // 在计算结果之前，随机选择一个事件
            const event = this.events[Math.floor(Math.random() * this.events.length)];
            const opponent = this.matchOpponent(slaveData.ranking.score);

            // 考虑事件效果影响胜率
            const result = Math.random() < 0.5 * event.effect;

            // 计算分数变化
            const scoreDiff = this.calculateScoreChange(
                slaveData.ranking.score,
                opponent.score,
                result
            );

            // 更新数据
            slaveData.ranking.score += scoreDiff;
            slaveData.ranking.matches++;
            slaveData.ranking.tier = this.getTier(slaveData.ranking.score);

            // 根据排位结果给予奖励
            const reward = Math.floor(Math.abs(scoreDiff) * 0.1);
            userData.currency = formatCurrency(userData.currency + reward);

            // 更新冷却时间
            userData.lastRankingTime = currentTime;
            await storagePlayerData(ID[1], ID[0], userData);

            await storagePlayerData(ID[1], slave, slaveData);

            const memberInfo = (await Bot.pickGroup(ID[1]).getMemberMap()).get(slave);
            return e.reply([
                segment.at(ID[0]), '\n',
                `当前事件：${event.name}（${event.desc}）\n`,
                `${memberInfo.nickname} VS ${opponent.name}\n`,
                `对手特性：${opponent.specialEffect}\n`,
                result ? '胜利！' : '失败！', '\n',
                `分数变化: ${scoreDiff > 0 ? '+' : ''}${scoreDiff}\n`,
                `当前分数: ${slaveData.ranking.score}\n`,
                `当前段位: ${slaveData.ranking.tier}\n`,
                `获得奖励: ${reward}金币`
            ]);
        } catch (error) {
            logger.error('处理排位赛请求时出错:', error);
            return e.reply(['处理请求时出错，请稍后再试']);
        }
    }

    // 匹配对手
    matchOpponent(score) {
        // 在相近分数范围内随机选择对手
        const validOpponents = this.opponents.filter(o =>
            Math.abs(o.score - score) <= 300
        );

        if (validOpponents.length === 0) {
            return this.opponents[Math.floor(Math.random() * this.opponents.length)];
        }

        return validOpponents[Math.floor(Math.random() * validOpponents.length)];
    }

    // 计算分数变化
    calculateScoreChange(score1, score2, isWin) {
        const K = 32;
        const E = 1 / (1 + Math.pow(10, (score2 - score1) / 400));
        return Math.floor(K * (isWin ? 1 - E : 0 - E));
    }

    // 获取段位
    getTier(score) {
        if (score < 1000) return '青铜';
        if (score < 1400) return '白银';
        if (score < 1800) return '黄金';
        if (score < 2200) return '铂金';
        return '钻石';
    }

    async showRanking(e) {
        if (!e.isGroup) return e.reply(['该功能只能在群内使用']);
        const ID = [e.user_id, e.group_id];

        // 确保群组和玩家数据存在
        await ensureGroupAndPlayerExist(ID[1], ID[0]);

        try {
            const userData = await getPlayerData(ID[1], ID[0]);
            if (!userData.slave || userData.slave.length === 0) {
                return e.reply(['你还没有奴隶，无法查看排位赛信息']);
            }

            let rankingInfo = ['【奴隶排位赛信息】\n'];

            for (const slaveId of userData.slave) {
                const slaveData = await getPlayerData(ID[1], slaveId);
                const memberInfo = (await Bot.pickGroup(ID[1]).getMemberMap()).get(Number(slaveId));

                if (!slaveData.ranking) {
                    slaveData.ranking = {
                        score: 1000,
                        tier: '青铜',
                        matches: 0
                    };
                    await storagePlayerData(ID[1], slaveId, slaveData);
                }

                rankingInfo.push(
                    `${memberInfo.nickname}\n`,
                    `段位：${slaveData.ranking.tier}\n`,
                    `分数：${slaveData.ranking.score}\n`,
                    `比赛场次：${slaveData.ranking.matches}\n`,
                    '---------------\n'
                );
            }

            rankingInfo.push(
                '\n【段位说明】\n',
                '青铜: 0-999分\n',
                '白银: 1000-1399分\n',
                '黄金: 1400-1799分\n',
                '铂金: 1800-2199分\n',
                '钻石: 2200分以上\n\n',
                '发送 #参加排位赛 [奴隶QQ] 开始比赛'
            );

            return e.reply(rankingInfo);
        } catch (error) {
            logger.error('查看排位赛信息时出错:', error);
            return e.reply(['查看信息时出错，请稍后再试']);
        }
    }
} 